package jsu.blogger.handler;

import io.jsonwebtoken.Claims;
import jakarta.websocket.Session;
import jsu.blogger.util.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;

public class WebSocketHandler{
    private static final Logger log = LoggerFactory.getLogger(WebSocketHandler.class);

    public static boolean isTokenValid(Session session) {
        boolean isValid = false;
//        System.out.println("WebSocket已建立,id:" + session.getId());
        // 获取路径参数
        Map<String, String> pathParams = session.getPathParameters();
        String uid = pathParams.get("uid");
        String token = pathParams.get("token");
//        System.out.println("uid:" + uid);
        // 验证 token 和 uid 是否匹配
        if (token != null && uid != null) {
            try {
                // 解析 token
                Claims claims = TokenUtil.parseJWT(token);
                // 可选：进一步验证 uid 是否与 token 中的用户信息匹配
                String uidFromToken = claims.get("uid", String.class);
                if (uidFromToken != null && uidFromToken.equals(uid)) {
                    isValid = true;
                    // 继续处理请求
                } else {
                    System.out.println("UID 不匹配");
                }
            } catch (Exception e) {
                log.error("解析失败，Token 不合法");
                e.printStackTrace();
            }
        } else {
            System.out.println("token或uid为空");
        }
        return isValid;
    }
}
